package com.itheima.test;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.*;

public class POI {
    @Test
    public void test1() {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(this.getClass().getResource("/hello.xlsx").getPath());
//            workbook = new XSSFWorkbook(new FileInputStream(new File("C:\\hello.xlsx")));
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            int firstRowNum = sheetAt.getFirstRowNum();
            int lastRowNum = sheetAt.getLastRowNum();
            for (Row cells : sheetAt) {
                short firstCellNum = cells.getFirstCellNum();
                short lastCellNum = cells.getLastCellNum();
                for (Cell cell : cells) {
                    System.out.println(cell.getStringCellValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() throws IOException {
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook("C:\\hello.xlsx");
//获取工作表，既可以根据工作表的顺序获取，也可以根据工作表的名称获取
        XSSFSheet sheet = workbook.getSheetAt(0);
//遍历工作表获得行对象
        for (Row row : sheet) {
            //遍历行对象获取单元格对象
            for (Cell cell : row) {
                //获取单元格中的值
                String value = cell.getStringCellValue();
                System.out.println(value);
            }
        }
        workbook.close();
    }

    @Test
    public  void test3() throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("陈安");
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("地址");

        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("1");
        row1.createCell(1).setCellValue("喜爱");
        row1.createCell(2).setCellValue("合肥");

        FileOutputStream fileInputStream = new FileOutputStream("c:\\a.xlsx");
        workbook.write(fileInputStream);
        fileInputStream.close();
        workbook.close();
    }
}
